package cn.lingyangwl.agile.system.manager;

import cn.lingyangwl.agile.model.constants.TenantCons;
import cn.lingyangwl.agile.model.enums.BoolEnum;
import cn.lingyangwl.agile.model.module.tenant.TenantContext;
import cn.lingyangwl.agile.system.mapper.SysDeptMapper;
import cn.lingyangwl.agile.system.mapper.SysUserDeptRelMapper;
import cn.lingyangwl.agile.system.model.entity.SysDept;
import cn.lingyangwl.agile.system.model.entity.SysUserDeptRel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
public class SysDeptManager extends ServiceImpl<SysDeptMapper, SysDept> {
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysUserDeptRelMapper userDeptMapper;

    public List<Long> listDeptIdByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<SysUserDeptRel> wrapper = Wrappers.<SysUserDeptRel>lambdaQuery()
                .select(SysUserDeptRel::getUserId).eq(SysUserDeptRel::getUserId, userId);
        return userDeptMapper.selectList(wrapper).stream().map(SysUserDeptRel::getDeptId)
                .collect(Collectors.toList());
    }

    public boolean hasChildByDeptId(Long deptId) {
        if (Objects.isNull(deptId)) {
            return false;
        }
        LambdaQueryWrapper<SysDept> wrapper = Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getDelFlag, BoolEnum.FALSE.getCode())
                .eq(SysDept::getParentId, deptId);
        return sysDeptMapper.selectCount(wrapper) > 0;
    }

    public SysDept getByCode(String deptCode) {
        LambdaQueryWrapper<SysDept> wrapper = Wrappers.<SysDept>lambdaQuery()
                .eq(SysDept::getDelFlag, BoolEnum.FALSE.getCode())
                .eq(SysDept::getDeptCode, deptCode);
        return sysDeptMapper.selectOne(wrapper);
    }

    public void deleteAllDept() {
        String tenantId = TenantContext.get().getTenantId();
        if (TenantCons.SYSTEM_TENANT_ID.equals(tenantId) || StringUtils.isEmpty(tenantId)) {
            log.warn("正常删除非法租户 {} 下的用户, 已拦截", tenantId);
            return;
        }
        LambdaQueryWrapper<SysDept> lqw = SysDept.lqw();
        this.remove(lqw);

        // 删除关系
        userDeptMapper.delete(SysUserDeptRel.lqw());
    }
}
